package com.wmh.baseservice.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component
public class CheckUtil {

    @Resource
    private MerchantInfoService merchantInfoService;

    private static MerchantInfoService staticMerchantInfoService;

    @PostConstruct
    private void init(){
        staticMerchantInfoService=merchantInfoService;
    }

    /**
     * 校验是否为同一个商家
     * @param rawId 对象的原商家id，比如商品对象的商家id
     * @param nowId 当前操作(request)拿到的商家id
     */
    public static String merchantCheck(Long rawId, Long nowId){
        MerchantInfo merchantInfo = staticMerchantInfoService.getByIdForUpdate(rawId);
        if (merchantInfo.getParentId()!=-1){
            MerchantInfo parentInfo = staticMerchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
            if (!parentInfo.getId().equals(nowId)){
                throw new ServiceException("非当前商家权限");
            }
        }else {
            if (!merchantInfo.getId().equals(nowId)){
                throw new ServiceException("非当前商家权限");
            }
        }
        return null;
    }
}
